'''
Python中的元类
    1. type
    2. metaclass
'''

# 1、
# class User():
#     def say(self, txt):
#         print('hi,%s' % txt)
#
# u = User()
# u.say('disen')

# 2、
# 2、1
# def say(self,txt):
#     print('hi,%s' % txt)

# type(class_name, bases_classes,attrs)
# class_name类名  bases_classes 类的继承的父类，是元祖类，空元祖（‘’）
# attrs 类的属性成员（方法和属性），是字典类型
User = type('User', (), {
    # 2.1
    # 'say':say

    # 2.2
    'say':lambda self,msg:'hi,%s' % msg
})
u = User()
# 2.1
# u.say('disen')

# 2.2
print(u.say('disen'))


# 3、
"""
type 元类实现类的ORM映射
Person()
    id = Column(String,max_length=20)
    name = Column(String,max_length=20)

create table table_name(field_name field_type ...)
"""

class BaseField():
    pass

class CharFiled(BaseField):
    def __init__(self, length):
        self.length = length

class IntField(BaseField):
    pass

class BaseModelMete(type):
    def __new__(cls,name, bases, attrs):
        print('--BaseModelMete--',name)
        print('--BaseModelMete--',bases)
        print('--BaseModelMete--', attrs)

        if name == 'Model':
            return type.__new__(cls, name , bases ,attrs)

        fields = {}
        for key,field in attrs.items():
            if isinstance(field, BaseField):
                fields[key] = field
        table = attrs.get('__tablename__',name.lower())

        attrs['fields'] = fields
        attrs['table'] = table

        return type.__new__(cls,name,bases,attrs)

class Model(metaclass=BaseModelMete):
    def create(self):
        print('--create---')

        sql = "create table %s(%s)"
        table_name = self.table
        columns = ['%s %s' % (key,'varchar(%s)' % field.length if isinstance(field, CharFiled) else 'integer')
                   for key,field in self.fields.items()]
        sql = sql % (table_name, ','.join(columns))
        print(sql)

    def save(self):
        pass

    def delete(self):
        pass

    def query(self):
        pass

class Person(Model):
    id = IntField()
    name = CharFiled(50)
    city = CharFiled(20)

p = Person()
p.create()